<template>
    <u-popup
        :show="show"
        ref="popup"
        @close="close"
        type="bottom"
        @touchmove.stop.prevent="
            () => {
                return
            }
        "
    >
        <view class="mian getHeight" id="main" :style="'direction:' + $t('dir')" :class="$t('dir') == 'rtl' ? 'rtl' : 'ltr'">
            <view class="top getHeight" id="top">
                <text>{{ title }}</text>
                <!-- <text class="iconfont close" @click.stop="close">&#xe7fa;</text> -->
                <view style="padding: 40rpx 30rpx 30rpx; z-index: 3">
                    <u-icon name="close" color="gray" size="20" style="" class="button" @click="close"></u-icon>
                </view>
            </view>
            <view v-if="isSearch" class="pa-md button" @click="selectAll">
                {{ $t('chakanquanbu') }}
            </view>
            <scroll-view scroll-x="true" @scroll="scroll" :show-scrollbar="false" class="nav getHeight" id="nav" :scroll-into-view="scrollIntoView">
                <template v-for="(item, index) in list">
                    <view @click="areaSelect(index)" :key="index" :id="index" class="nav-item button" :class="areaIndex == index ? 'nav-item-a' : ''" v-if="index != 0">
                        <text>{{ item['name' + $t('k')] }}</text>
                    </view>
                </template>

                <!-- <view class="bottomBorder" :style="'left:' + navBottomLeft + 'px'"></view> -->
            </scroll-view>
            <!-- <swiper class="swiper getHeight" :disable-touch="true" :current="current" :style="'height:' + swiperH + 'px'">
                <swiper-item v-for="(type, idx) in [1, 2, 3]" :key="idx" :id="'sw' + type"> -->
            <view class="row swiper">
                <view v-for="(type, idx) in [1, 2, 3]" :key="idx" :id="'sw' + type" v-show="current == idx">
                    <scroll-view scroll-y="true" scroll-with-animation scroll-anchoring :scroll-into-view="id2" @scroll="scroll" :show-scrollbar="false" class="swiper-list">
                        <view class="area-item" v-for="(item, index) in getList" :key="index" :id="'area' + index">
                            <!-- <text :class="id == item._id + type ? 'area-item-id area-item-id-sticky' : 'area-item-id'" :id="item._id + type">{{ item._id }}</text> -->
                            <view class="swiper-list2">
                                <text class="button" :class="proCode == item2.code ? 'area-item-name area-item-name-a' : 'area-item-name'" @click="itemSelect(item2, idx)" v-for="(item2, index2) in item.data" :key="index2">
                                    <text class="iconfont" v-if="proCode == item2.code || cityCode == item2.code || disCode == item2.code">&#xe674;</text>
                                    {{ item2['name' + $t('k')] }}
                                    <!-- <view>{{ item2.name }}</view>
                                        <view>{{ item2.name_ug }}</view> -->
                                </text>
                            </view>
                        </view>
                    </scroll-view>
                </view>
            </view>
            <!-- </swiper-item>
            </swiper> -->
            <!-- <view class="slider-right">
                <view class="slider-list">
                    <text class="slider-item" v-for="(item, index) in areaIndex == 0 ? provinceList : areaIndex == 1 ? cityList : areaIndex == 2 ? disList : townList" :key="index" @click="sliderSelect(item._id + (areaIndex + 1))">{{ item._id }}</text>
                </view>
            </view> -->
        </view>
    </u-popup>
</template>

<script>
import provinceData from './city-china.js'
export default {
    name: 'area-choose',
    props: {
        show: {
            type: Boolean,
            default: false,
        },
        title: {
            type: String,
            default: '请选择所在地区',
        },
        isSearch: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            list: [this.$t('please_select'), '', ''],
            areaIndex: 0,
            navBottomLeft: 0,
            scrollIntoView: 'area0',
            code: '',
            provinceList: [], //省
            proCode: -1,
            cityList: [],
            cityCode: -1,
            disList: [],
            disCode: -1,
            townList: [],
            townCode: -1,
            swiperH: 300, //列表高
            current: 0, //当前滑块
            id: '', //地址编号A、B、C、...
            id2: '',
            scrollTopList: [
                {
                    id: 'A',
                    top: 0,
                },
            ],
            scrollTopListAll: {},
            provinceData: [],
        }
    },
    computed: {
        getList() {
            return this.areaIndex == 0 ? this.provinceList : this.areaIndex == 1 ? this.cityList : this.areaIndex == 2 ? this.disList : this.townList
        },
    },
    watch: {
        show(newValue, oldValue) {
            this.show1()
        },
    },
    methods: {
        selectAll() {
            this.close()
            this.$emit('confirm', {
                address: '',
                address_ug: '',
                full_address: '',
                full_address_ug: '',
                addressList: [
                    {
                        name: '',
                        name_ug: '',
                    },
                    {
                        name: '',
                        name_ug: '',
                    },
                    {
                        name: '',
                        name_ug: '',
                    },
                ],
                proCode: '',
                cityCode: '',
                disCode: '',
            })
        },
        close() {
            this.$emit('close')
        },
        show1() {
            this.provinceList = uni.getStorageSync('provinceList')
            if (!this.provinceList) {
                this.getData()
                let obj = {
                    _id: '66567c913d029c65e91a09bc',
                    code: '650000',
                    name: '新疆维吾尔自治区',
                    name_ug: 'شىنجاڭ ئۇيغۇر ئاپتونوم رايونى',
                    pinyin: 'xinjiangweiwuerzizhiqu',
                    zip_code: '0',
                    type: 0,
                    first_letter: 'X',
                }
                this.itemSelect(obj, 0)
            } else {
                this.getScrollT(0, this.provinceList.length)
                this.current = 0
                setTimeout(() => {
                    this.areaSelect(0)
                }, 200)
            }

            setTimeout(() => {
                this.getSwiperH()
            }, 200)
        },
        onchange(e) {
            const value = e.detail.value
        },
        scroll(e) {
            // console.log(this.scrollTopList,"-----")
            if (this.scrollTopList == undefined) return
            this.scrollTopList.some((item, index) => {
                if (e.detail.scrollTop > item.top) {
                    this.id = item.id
                }
            })
        },
        areaSelect(index) {
            this.$nextTick(() => {
                // 选中头部地址项
                this.areaIndex = index
                this.current = index
                //自动滚动
                this.scrollIntoView = 'area' + index
                let widthAll = 0
                return
                for (let i = 0; i < index + 1; i++) {
                    var query = uni.createSelectorQuery().in(this)
                    var idView = '#area' + i
                    query.select(idView).boundingClientRect()
                    query.exec((res) => {
                        console.log('res:', res)

                        if (i < index) {
                            widthAll += res[0].width
                        }
                        if (i == index) {
                            this.navBottomLeft = widthAll - (res[0].width - uni.upx2px(60)) / 2
                        }
                    })
                }
                this.scrollTopList = this.scrollTopListAll[index]
            })
        },
        sliderSelect(id) {
            this.id2 = id
        },
        getSwiperH() {
            // var query = uni.createSelectorQuery().in(this)
            // query
            //     .selectAll('.getHeight')
            //     .boundingClientRect()
            //     .exec((res) => {
            //         if (res[0].length > 0) {
            //             this.swiperH = res[0][0].height - res[0][1].height - res[0][2].height - uni.upx2px(20)
            //         } else {
            //             setTimeout(() => {
            //                 this.getSwiperH()
            //             }, 200)
            //         }
            //     })
        },
        getScrollT(type, length) {
            // var query = uni.createSelectorQuery().in(this)
            // query
            //     .selectAll('#sw' + (type + 1) + ' .area-item-id')
            //     .boundingClientRect()
            //     .exec((res) => {
            //         if (res[0].length == length) {
            //             this.scrollTopList = []
            //             let firstTop = res[0][0].top
            //             res[0].forEach((item, index) => {
            //                 let obj = {
            //                     id: item.id,
            //                     top: item.top - firstTop,
            //                 }
            //                 this.scrollTopList.push(obj)
            //             })
            //             this.scrollTopListAll[type] = this.scrollTopList
            //         } else {
            //             setTimeout(() => {
            //                 this.getScrollT(type, length)
            //             }, 200)
            //         }
            //     })
        },
        itemSelect(item, type) {
            switch (type) {
                case 0:
                    this.proCode = item.code
                    break
                case 1:
                    this.cityCode = item.code
                    break
                case 2:
                    this.disCode = item.code
                    break
                case 3:
                    this.townCode = item.code

                    break
                default:
                    break
            }
            this.list.forEach((item2, index2) => {
                if (index2 == type) {
                    this.$set(this.list, type, { name: item.name, name_ug: item.name_ug })

                    if (index2 < 2) {
                        // this.$set(this.list, type + 1, this.$t('please_select'))
                        this.getData(item.code, type + 1)
                    } else {
                        setTimeout(() => {
                            this.areaSelect(type)
                        }, 200)
                    }
                }
                if (index2 > type + 1) {
                    // this.$set(this.list, index2, '')
                }
            })
            // console.log('this.list:', this.list)

            if (type == 2) {
                this.close()

                let address = []
                let address_ug = []
                let full_address = []
                let full_address_ug = []
                for (var i in this.list) {
                    full_address += this.list[i].name
                    full_address_ug += ' ' + this.list[i].name_ug
                    if (i != 0) {
                        address += this.list[i].name
                        address_ug += ' ' + this.list[i].name_ug
                    }
                }
                this.$emit('confirm', {
                    address,
                    address_ug,
                    full_address,
                    full_address_ug,
                    addressList: this.list,
                    proCode: this.proCode,
                    cityCode: this.cityCode,
                    disCode: this.disCode,
                })
            }
        },

        groupByFirstLetter(data) {
            // 先进行分组
            let grouped = data.reduce((acc, item) => {
                let letter = item.first_letter
                let group = {
                    _id: letter,
                    data: [],
                }

                if (!acc.find((g) => g._id === letter)) {
                    acc.push(group)
                } else {
                    group = acc.find((g) => g._id === letter)
                }

                group.data.push(item)
                return acc
            }, [])

            // 对分组进行排序
            // grouped.sort((a, b) => a._id.localeCompare(b._id))

            return grouped
        },
        getData(code = '', type = 0) {
            const plist = provinceData.filter((item, index) => {
                if (type == 0) {
                    return item.type == type
                } else {
                    return item.parent_code == code && item.type == type
                }
            })

            let list = this.groupByFirstLetter(plist)

            switch (type) {
                case 0:
                    this.provinceList = list
                    // uni.setStorageSync('provinceList', list)
                    break
                case 1:
                    this.cityList = list
                    break
                case 2:
                    this.disList = list
                    break
                case 3:
                    this.townList = list
                    break
                default:
                    break
            }
            if (list.length > 0) {
                this.getScrollT(type, list.length)
            }
            this.current = type
            this.areaSelect(type)
        },
    },
}
</script>


<style lang="scss" scoped>
/*每个页面公共css */
@font-face {
    font-family: 'iconfont';
    src: url('./iconfont.ttf') format('truetype');
}

.iconfont {
    font-family: iconfont;
}

.mian {
    height: 75vh;
    width: 100%;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    position: relative;
    padding-bottom: 20rpx;

    .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30rpx;
        font-size: 32rpx;
        font-weight: bold;

        .iconfont {
            font-size: 40rpx;
        }
    }

    .nav {
        white-space: nowrap;
        width: 100%;
        position: relative;
        padding: 0rpx 20rpx;
        border-bottom: 1px solid #ddd;

        .bottomBorder {
            position: absolute;
            width: 60rpx;
            height: 6rpx;
            background: linear-gradient(to right, rgba(255, 0, 0, 1), rgba(255, 0, 0, 0.5));
            bottom: 5rpx;
            left: 0rpx;
            transition: left 0.5s ease;
        }

        .nav-item {
            padding: 10rpx 20rpx;
            display: inline-block;
            text-align: center;
            font-size: 28rpx;
        }

        .nav-item-a {
            color: rgb(201, 22, 35) !important;
            // position: relative;
        }
    }

    .swiper {
        height: 1070rpx;
        margin-top: 20rpx;

        .swiper-list {
            height: 100%;
            display: flex;
            flex-direction: column;
            position: relative;

            .area-item {
                font-size: 30rpx;

                .area-item-id {
                    padding: 20rpx 44rpx 0;
                    border-bottom: 1rpx solid #f0ecf2;
                    font-weight: bold;
                    display: block;
                }

                .area-item-id-sticky {
                    position: sticky;
                    top: 0;
                    background-color: #ffffff;
                    transition: all 0.1s;
                }

                .swiper-list2 {
                    display: flex;
                    flex-direction: column;

                    .area-item-name {
                        padding: 20rpx 40rpx 20rpx;
                        font-weight: 400;

                        .iconfont {
                            color: rgb(201, 22, 35);
                            margin-right: 10rpx;
                        }
                    }

                    .area-item-name-a {
                        color: rgb(201, 22, 35);
                    }
                }
            }
        }
    }

    .slider-right {
        position: absolute;
        right: 0rpx;
        top: 80rpx;
        bottom: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 20rpx;

        .slider-list {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #ebe8ee;
            border-radius: 20rpx;
        }

        .slider-item {
            padding: 10rpx 10rpx;
            font-size: 26rpx;
            color: #24292e;

            &:first-child {
                padding-top: 20rpx;
            }

            &:last-child {
                padding-bottom: 20rpx;
            }
        }
    }
}
</style>